<?php
/**
 * This interface will handle medical center monitoring deletion
 * 
 * @author Xavier VILAIN
 * @package Nawa\MedicalStudy\MedicalCenter\Patient
 * @license #license-nawa#
 * 
 */

use Fox\Utilities\Dates;
use Nawa\MedicalStudy\MedicalCenter\Patient;
use Nawa\MedicalStudy\MedicalCenter;
use Fox\Behaviors;
use Fox\Generator;
$xview = Xview::instance();
$msid = $xview->val('msid');
$mcid = $xview->val('mcid');
$monitoringid = $xview->val('monitoringid');
$keys = $xview->val(array('msid','mcid','monitoringid'));
$confirmation = $xview->val('confirmation',false);

$title =  Msg(Nawa\Messages::BUNDLE,Nawa\Messages::MONITORING_DELETION_TITLE);
if(empty($monitoringid)) {
	// Not possible display an error message
	Fox\Message::Error(Msg(Nawa\Messages::BUNDLE,Nawa\Messages::MONITORING_DELETION_ERROR));
} else {
	try {
		$ms = $xview->component('medicalstudies','object',$keys);
		$centerPartner = $ms->findMedicalCentersPartners($ms->getInlineId().':'.$mcid);
		$monitoring = $centerPartner->findMonitorings($centerPartner->getInlineId().':'.$monitoringid);
		$formatedDate = Dates::dateTimeToFullString($monitoring->monitoring_date);
		$message = Msg(Nawa\Messages::BUNDLE,Nawa\Messages::MONITORING_DELETION_CONFIRMATION,
						$formatedDate);
	} catch(Fox\Object\Exception\NotExist $e) {
		Fox\Message::Error(Msg(Nawa\Messages::BUNDLE,Nawa\Messages::MONITORING_DELETION_ERROR));
	}
}

// We are dealing with a 
if(!Fox\Message::errors() && $confirmation) {
	try {
		//@TODO add authorization check
		$monitoring->delete();
		Fox\Message::Success(Msg(Nawa\Messages::BUNDLE,Nawa\Messages::MONITORING_DELETION_SUCCESS));
	} catch(Fox\Object\Exception\Save $e) {
		Fox\Message::Error($e);
	} catch(Fox\Object\Exception\NotExist $e) {
		Fox\Message::Error($e);
	}
	echo $xview->messages(true,true);
	exit;
}
if(!Fox\Message::errors()) {
	$callback = Generator::redirect(Generator::url('medicalstudies','medicalcenter',null,array('msid' => $msid,'mcid' => $mcid)));
	$link1 = Generator::ajax(Generator::url('medicalstudies','medicalcenter','monitoring_delete',
								array('msid' => $msid,
									'mcid' => $mcid,
									'monitoringid' => $monitoringid)), '&confirmation=true', $callback);
	$popup = new Fox\Popup\ToConfirm('pDeletion',$title,$message,$link1);
	$popup->footer()->item(Fox\Popup\ToConfirm::ACTION_YES)->behaviors(Behaviors::value('close'));
} else {
	$message = $xview->messages(true);
	$popup = new Fox\Popup\Help('pDeletion',$title,$message);
}
echo $popup->display();